package com.ljkj.cordial.chat.presenter;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;

import com.lanjiu.lib.NettyHost;
import com.lanjiu.pro.business.BusinessProtocolMessageStandard;
import com.lanjiu.pro.business.BusinessProtocolMessages;
import com.ljkj.cordial.chat.activity.ChatMainActivity;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.notify.NotificationUtils;
import com.ljkj.cordial.chat.presenter.response.AResponseBusinessPresenter;
import com.ljkj.cordial.chat.presenter.response.IViewRefreshListener;
import com.ljkj.cordial.chat.presenter.response.ResponseBusinessFactory;
import com.ljkj.cordial.chat.util.DeleteHistoryUtil;
import com.ljkj.cordial.lengthtcpheartbeat.OnClientConnectedListener;
import com.ljkj.cordial.lengthtcpheartbeat.OnHeartbeatReceiveListener;
import com.ljkj.cordial.lengthtcpheartbeat.ResponseChat;
import com.ljkj.cordial.lengthtcpheartbeat.TcpLengthHeartbeatBroadcastReceive;
import com.nic.view.util.DateTimeUtil;
import com.nic.view.util.JLog;

import java.lang.ref.WeakReference;


/**
 * 主要长连接业务
 */
public class ChatMainPresenter extends ResponseChat {
    private Activity activity;
    private boolean isOnScreen = true;
    private volatile long timestamp;

    public ChatMainPresenter(Activity activity) {
        this.activity = activity;
        TcpLengthHeartbeatBroadcastReceive.registerReceiver(ChatApp.getInstance().getApplicationContext());
        TcpLengthHeartbeatBroadcastReceive.setOnHeartbeatReceiveListener(new OnHeartbeatReceiveListener() {
            @Override
            public void receiveHeartbeat(String fromId) {
                //记录游客在线时间节点
//                if (!ChatApp.getInstance().isRegister() && !TextUtils.isEmpty(fromId) && fromId.length() == 9) {
//                    long firstTagTime = (long) SharedUtils.get(activity, fromId.substring(0, fromId.length() - 1), 0L);
//                    if (firstTagTime == 0L) {
//                        SharedUtils.put(activity, fromId.substring(0, fromId.length() - 1), System.currentTimeMillis());
//                    }
//                }
                String logTime = DateTimeUtil.getCurrentDateHHMMSS();
                JLog.i(logTime);
                if (!isOnScreen && logTime.split(":")[0].equals("02")) {
                    //两点清理,结束关闭前台进程
                    DeleteHistoryUtil.getInstance().clear(activity, (clearCyc, isClear) -> {
                        if (isClear && clearCyc != Canstants.CLEAR_TIME) {
//                            IMSClientHelper.getInstance().close();
//                            TcpLengthHeartbeatBroadcastReceive.loginOut();
                            NotificationUtils.clearNotify(activity);
                            ChatApp.getInstance().quitApp();
                        }
                    });
                }
            }
        });

    }



    /**
     * 拉起长连接
     */
    public void connect() {
        String[] address = NettyHost.BUSINESS_COMMUNICATION_HOST.split(":");
        TcpLengthHeartbeatBroadcastReceive.connect(ChatApp.getInstance().getUserId() + "1", address[0], Integer.parseInt(address[1]));
        TcpLengthHeartbeatBroadcastReceive.setOnDispenseResponseListener(ChatMainPresenter.this);
    }


    public void setLengthConnectedListener(OnClientConnectedListener onClientConnectedListener) {
        TcpLengthHeartbeatBroadcastReceive.setOnClientConnectedListener(new OnClientConnectedListener() {
            @Override
            public void onConnected() {
                if (activity == null || activity.isFinishing()) {
                    return;
                }
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (onClientConnectedListener != null) {
                            onClientConnectedListener.onConnected();
                        }
                    }
                });

            }
        });

    }

    public void onDestroy() {
        TcpLengthHeartbeatBroadcastReceive.unRegisterReceiver(ChatApp.getInstance());
    }

    public void onScreen(boolean onScreen) {
        isOnScreen = onScreen;
        TcpLengthHeartbeatBroadcastReceive.setOnScreen(onScreen);
//        if (onScreen) {
//            TableFileCacheUtil.getInstance().downLoadChatFilesToLocTable(activity);
//        }
    }

    @Override
    public void setHead(BusinessProtocolMessageStandard.Head head) {
        super.setHead(head);
        timestamp = head.getTimestamp();
    }

    @Override
    public void onGroupCreateProtocol(BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType dataType, String msgType, BusinessProtocolMessages.GroupCreateProtocol response) {
        super.onGroupCreateProtocol(dataType, msgType, response);
        responseHandler(dataType, msgType, response);
    }

    @Override
    public void onNotificationsProtocol(BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType dataType, String msgType, BusinessProtocolMessages.NotificationsProtocol response) {
        super.onNotificationsProtocol(dataType, msgType, response);
        responseHandler(dataType, msgType, response);
    }

    @Override
    public void onSysNotifyProtocol(BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType dataType, String msgType, BusinessProtocolMessages.SysNotifyProtocol response) {
        super.onSysNotifyProtocol(dataType, msgType, response);
        responseHandler(dataType, msgType, response);
    }

    @Override
    public void onFriendChatProtocol(BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType dataType, String msgType, BusinessProtocolMessages.FriendChatProtocol response) {
        super.onFriendChatProtocol(dataType, msgType, response);
        responseHandler(dataType, msgType, response);
    }

    @Override
    public void onGroupChatProtocol(BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType dataType, String msgType, BusinessProtocolMessages.GroupChatProtocol response) {
        super.onGroupChatProtocol(dataType, msgType, response);
        responseHandler(dataType, msgType, response);
    }

    @Override
    public void onFriendAddProtocol(BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType dataType, String msgType, BusinessProtocolMessages.FriendAddProtocol response) {
        super.onFriendAddProtocol(dataType, msgType, response);
        responseHandler(dataType, msgType, response);
    }

    @Override
    public void onGroupMemberAddProtocol(BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType dataType, String msgType, BusinessProtocolMessages.GroupMemberAddProtocol response) {
        super.onGroupMemberAddProtocol(dataType, msgType, response);
        responseHandler(dataType, msgType, response);
    }

    @Override
    public void onFriendDeleteProtocol(BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType dataType, String msgType, BusinessProtocolMessages.FriendDeleteProtocol response) {
        super.onFriendDeleteProtocol(dataType, msgType, response);
        responseHandler(dataType, msgType, response);

    }

    @Override
    public void onGroupInfoProtocol(BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType dataType, String msgType, BusinessProtocolMessages.GroupInfoProtocol response) {
        super.onGroupInfoProtocol(dataType, msgType, response);
        responseHandler(dataType, msgType, response);
    }

    @Override
    public void onGroupMemberDeleteProtocol(BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType dataType, String msgType, BusinessProtocolMessages.GroupMemberDeleteProtocol response) {
        super.onGroupMemberDeleteProtocol(dataType, msgType, response);
        responseHandler(dataType, msgType, response);
    }

    @Override
    public void onGroupAnnouncementProtocol(BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType dataType, String msgType, BusinessProtocolMessages.GroupAnnouncementProtocol response) {
        super.onGroupAnnouncementProtocol(dataType, msgType, response);
        responseHandler(dataType, msgType, response);
    }

    @Override
    public void onFriendInfoProtocol(BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType dataType, String msgType, BusinessProtocolMessages.FriendInfoProtocol response) {
        super.onFriendInfoProtocol(dataType, msgType, response);
        responseHandler(dataType, msgType, response);
    }

    @Override
    public void onDelFriendOffMessageProtocol(BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType dataType, String msgType, BusinessProtocolMessages.DelFriendOffMessageProtocol response) {
        super.onDelFriendOffMessageProtocol(dataType, msgType, response);
        responseHandler(dataType, msgType, response);
    }

    @Override
    public void onDelGroupMessageProtocol(BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType dataType, String msgType, BusinessProtocolMessages.DelGroupOffMessageProtocol response) {
        super.onDelGroupMessageProtocol(dataType, msgType, response);
        responseHandler(dataType, msgType, response);
    }

    @Override
    public void onMessageClearProtocol(BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType dataType, String msgType, BusinessProtocolMessageStandard.Head response) {
        super.onMessageClearProtocol(dataType, msgType, response);
        responseHandler(dataType, msgType, response);
    }

    @Override
    public void onLogoutProtocol(BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType dataType, String msgType, BusinessProtocolMessages.LogoutProtocol response) {
        super.onLogoutProtocol(dataType, msgType, response);
        ResponseBusinessFactory.create(dataType, new IViewRefreshListener() {
            @Override
            public void onViewRefresh(Activity activity) {
                if (activity != null && !activity.isFinishing() && listener != null) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            listener.onLoginOut();
                        }
                    });
                }

            }
        }).onResponse(activity, isOnScreen, msgType, response);
    }

    private void responseHandler(BusinessProtocolMessageStandard.UnifiedEntranceMessage.DataType dataType, String msgType, Object response) {
        AResponseBusinessPresenter factory = ResponseBusinessFactory.create(dataType, new IViewRefreshListener() {
            @Override
            public void onViewRefresh(Activity activity) {
                refresh();
            }
        });
        factory.onResponse(activity, isOnScreen, msgType, response);
        factory.setMsgTime(timestamp);
    }


    private void refresh() {
        if (activity != null && !activity.isFinishing() && onNotifyListener != null) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    onNotifyListener.onChatContent();
                }
            });
        }
    }


    private OnNotifyListener onNotifyListener;

    public void setOnNotifyListener(OnNotifyListener onNotifyListener) {
        this.onNotifyListener = onNotifyListener;
    }

    public interface OnNotifyListener {
        void onChatContent();
    }

    private OnLoginoutListener listener;

    public void setLoginoutListener(OnLoginoutListener listener) {
        this.listener = listener;
    }


    public interface OnLoginoutListener {
        void onLoginOut();
    }
}
